package com.tc.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.tc.constant.RedisConstants;
import com.tc.common.enums.ResponseCodeEnum;
import com.tc.common.exception.BizException;
import com.tc.model.vo.SendVerificationCodeReqVO;
import com.tc.common.response.Response;
import com.tc.service.VerificationService;
import com.tc.sms.AliyunSmsHelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Slf4j
@Component
public class VerificationServiceImpl implements VerificationService {
    @Resource
    // 因为要存储到Redis
    private RedisTemplate redisTemplate;

    @Resource(name = "taskExecutor")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Resource
    private AliyunSmsHelper aliyunSmsHelper;
    @Override
    public Response<?> send(SendVerificationCodeReqVO sendVerificationCodeReqVO) {
        String phone = sendVerificationCodeReqVO.getPhone();
        // 构建redis key
        String buildVerification_key = RedisConstants.buildVerification(phone);
        // 查询 redis key 是否已经存在
        Boolean ishasKey = redisTemplate.hasKey(buildVerification_key);
        if (ishasKey){
            // 如果存在 抛出异常 提示用户稍后重试
                throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }
        // 如果不存在 保存 然后 调用短信发送服务
        // 生成6位随机验证码
        String rand_verification_code = RandomUtil.randomNumbers(6);
        log.info("手机号：{}, 已生成随即验证码：{}", phone, rand_verification_code);
        threadPoolTaskExecutor.submit(() -> {
            String signName = "阿里云短信测试";
            String templateCode = "SMS_154950909";
            String templateParam = String.format("{\"code\":\"%s\"}", rand_verification_code);
            aliyunSmsHelper.sendMessage(signName, templateCode, phone, templateParam);
        });
        // 保存到redis
        redisTemplate.opsForValue().set(buildVerification_key, rand_verification_code, 3, TimeUnit.MINUTES);
        return Response.success();
    }
}
